package com.itg.vms.dao.impl;

import com.itg.vms.dao.SysMenuDao;
import com.itg.vms.entity.MenuKey;
import com.itg.vms.entity.SysMenu;
import com.itg.vms.entity.SystemMenu;
import com.itg.vms.util.C3P0Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @create 2023年03月07日 01:52:18
 */
public class SysMenuDaoImpl implements SysMenuDao {

    /**
     * 数据操作对象
     */
    QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

    /**
     * 查询菜单列表
     *
     * @return
     */
    @Override
    public List<SystemMenu> getSystemMenuByStatusAndSort() {

        String sql = "select * from vms.sys_menu";
        List<SystemMenu> query = null;
        try {
            query = queryRunner.query(sql, new BeanListHandler<>(SystemMenu.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    /**
     * 根据菜单id更新菜单状态
     *
     * @param id     菜单id
     * @param status 要更新的状态
     * @return 影响的行数
     */
    @Override
    public int updateMenuStatus(Integer id, Integer status) {

        String sql = "update vms.sys_menu set status = ? where id = ?";
        int update = 0;
        try {
            update = queryRunner.update(sql, status, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }

    /**
     * 得到所有菜单
     *
     * @param status 状态
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> findAllByStatusOrderBySort(Boolean status) {
        String sql = "select * from  vms.sys_menu where status = 1  ORDER BY pid,sort";
        List<Map<String, Object>> list = null;
        List<SysMenu> menuList = new ArrayList<>();
        try {
            list = queryRunner.query(sql, new MapListHandler());
            //遍历数据
            for (Map<String, Object> objectMap : list) {
                SysMenu sysMenu = new SysMenu();
                MenuKey menuKey = new MenuKey();

                BeanUtils.populate(sysMenu, objectMap);
                BeanUtils.populate(menuKey, objectMap);

                sysMenu.setKey(menuKey);

                menuList.add(sysMenu);
            }
        } catch (SQLException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return menuList;
    }
}